import React, { useEffect, useState } from 'react';
import { BrowserRouter as Router, Route, Routes, Navigate, useLocation } from 'react-router-dom';
import { Layout, message } from 'antd';
import './App.css';

// 导入布局组件
import AppFooter from './components/layout/Footer';

// 导入页面组件
import Home from './pages/Home';
import DeviceListPage from './pages/DeviceListPage';
import PluginListPage from './pages/PluginListPage';
import MarketPage from './pages/MarketPage';
import UserList from './pages/UserList';
import NotFound from './pages/NotFound';
import Login from './pages/Login';

const { Content } = Layout;

// 路由保护组件
const RequireAuth = ({ children }) => {
  const location = useLocation();
  const token = localStorage.getItem('token');

  if (!token) {
    // 用户未登录，重定向到登录页面
    message.warning('请先登录');
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  return children;
};

// 主应用布局组件 - 移除了左侧菜单和顶部导航
const AppLayout = ({ children }) => {
  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Layout style={{ padding: '24px' }}>
        <Content
          style={{
            background: '#fff',
            borderRadius: '2px',
            minHeight: 280,
            marginBottom: '24px'
          }}
        >
          {children}
        </Content>
        <AppFooter />
      </Layout>
    </Layout>
  );
};

function App() {
  // 检查是否已登录
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  useEffect(() => {
    const token = localStorage.getItem('token');
    setIsLoggedIn(!!token);
  }, []);

  return (
    <Router>
      <Routes>
        {/* 公开路由 */}
        <Route path="/login" element={<Login />} />

        {/* 需要登录的路由 */}
        <Route
          path="/"
          element={
            <RequireAuth>
              <AppLayout>
                <Home />
              </AppLayout>
            </RequireAuth>
          }
        >
          {/* 默认重定向到设备列表 */}
          <Route index element={<Navigate to="/device/list" replace />} />
          <Route path="device/list" element={<DeviceListPage />} />
          <Route path="plugin/list" element={<PluginListPage />} />
          <Route path="market" element={<MarketPage />} />
        </Route>

        <Route
          path="/users"
          element={
            <RequireAuth>
              <AppLayout>
                <UserList />
              </AppLayout>
            </RequireAuth>
          }
        />

        {/* 404 路由 */}
        <Route
          path="*"
          element={
            <RequireAuth>
              <AppLayout>
                <NotFound />
              </AppLayout>
            </RequireAuth>
          }
        />
      </Routes>
    </Router>
  );
}

export default App; 